package org.ghost.spring.cloud.config.server.demo.common.component;

import org.apache.commons.lang3.StringUtils;
import org.ghost.spring.cloud.config.server.demo.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

@Component
public class RequestContext implements IRequestContext {

    @Autowired
    private HttpServletRequest httpServletRequest;

    private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();

    private String id;

    private Locale locale = Locale.SIMPLIFIED_CHINESE;

    public static RequestContext getContext() {
        RequestContext result = CONTEXT.get();

        if (result == null) {
            result = new RequestContext();
            CONTEXT.set(result);
        }

        return result;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public static void remove() {
        CONTEXT.remove();
    }

//    public String getRequestId() {
//        return RequestThread.getUUID();
//    }


    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    @Override
    public String getRemoteIp() {
        String ip = httpServletRequest.getHeader("X-Real-IP");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = httpServletRequest.getHeader("X-Forwarded-For");
        if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return httpServletRequest.getRemoteAddr();
        }
    }

    @Override
    public Integer getSourceChannel() {
        Integer sourceChannel = NumberUtil.toInt(httpServletRequest.getHeader("sourceChannel"), 0);
        return sourceChannel != 0 ? sourceChannel : NumberUtil.toInt(httpServletRequest.getParameter("sourceChannel"), 0);
    }
}
